﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BCAMap.AMap;
using BCAMap.AMap.Dto;
using BCCommon;
using BCCommon.TMS.Transport;
using BCData.Common.Area;
using BCData.TMS.MallInterface.MallOrder;
using BCDto.Common.Area;
using BCDto.Location.Branches;
using BCDto.MallInterface;
using BCDto.TMS.Fence;
using BCDto.TMS.MallInterface;
using BCEntity.Common.Area;
using BCEntity.TMS.MallInterface.MallOrderAddress;
using BCService.TMS.Agent.AgentBranchesConfig;
using BCService.TMS.Fence;
using BCService.TMS.MallInterface;
using BCService.TMS.MallInterface.MallOrder;
using BCService.Utils;
using Newtonsoft.Json;
using BCCommon.Extensions;

namespace BCService.MallInterface
{
    /// <summary>
    /// 商城接口服务
    /// </summary>
    public class MallInterfaceService : IMallInterfaceService
    {
        private IProvinceData provinceData;
        private ICityData cityData;
        private ICountyData countyData;
        private IRunErrandService runErrandService;
        private IVehicleSelectService vehicleSelectService;
        private IMallOrderService mallOrderService;
        private IAgentBranchesConfigService agentBranchesConfigService;

        #region 构造函数
        public MallInterfaceService(IProvinceData provinceData,
            ICityData cityData,
            ICountyData countyData,
            IRunErrandService runErrandService,
            IVehicleSelectService vehicleSelectService,
            IMallOrderService mallOrderService,
            IAgentBranchesConfigService agentBranchesConfigService)
        {
            this.provinceData = provinceData;
            this.cityData = cityData;
            this.countyData = countyData;
            this.runErrandService = runErrandService;
            this.vehicleSelectService = vehicleSelectService;
            this.mallOrderService = mallOrderService;
            this.agentBranchesConfigService = agentBranchesConfigService;
        }
        #endregion

        #region 新建商城订单
        private void AddMallOrder(MallOrderDto mallOrderDto)
        {
            mallOrderService.Add(mallOrderDto);
        }
        #endregion

        #region 费用计算
        public IEnumerable<MallOrderResposeDto> CostCalc(MallOrderDto mallOrderDto)
        {
            var dto = Calc(mallOrderDto);
            if(dto!=null && dto.Any())
            {
                mallOrderService.UpdateOrderTransportCost(mallOrderDto.MallOrderNo, JsonExtensions.ObjectToJson(dto));
            }
            return dto;
        }
        public IEnumerable<MallOrderResposeDto> Calc(MallOrderDto mallOrderDto)
        {
            AddMallOrder(mallOrderDto);

            List<MallOrderResposeDto> resultList = new List<MallOrderResposeDto>();

            decimal weight = 0;
            mallOrderDto.MallGoodsList.ForEach(s => weight += (s.GoodsWeight * s.GoodsQuantity));

            if (!string.IsNullOrWhiteSpace(mallOrderDto.WarehouseID))
            {
                //仓发货 
                if(weight<=10 )
                {
                    var rst = runErrandService.GetResult(mallOrderDto);
                    if(rst.Result)
                    {
                        resultList.Add(rst);
                        mallOrderService.UpdateOrderTransportBusinessType(mallOrderDto.MallOrderNo, TransportBusinessType.RunErrands);
                        return resultList;
                    }
                }
                else
                {
                    resultList.Add( vehicleSelectService.GetResult(mallOrderDto));
                    mallOrderService.UpdateOrderTransportBusinessType(mallOrderDto.MallOrderNo, TransportBusinessType.SmallPieces);
                    return resultList;
                }

            }
            else
            {
                //商户发货

                if (weight <= 10)
                { 
                    var rst = runErrandService.GetResult(mallOrderDto);
                    if (rst.Result)
                    {
                        resultList.Add(rst);
                        mallOrderService.UpdateOrderTransportBusinessType(mallOrderDto.MallOrderNo, TransportBusinessType.RunErrands);
                        return resultList;
                    }
                    else
                    {
                        if (rst.IsBeginCalcCost)
                        {
                            resultList.Add(rst);
                            return resultList;
                        }

                        //需要拆单
                        //1.获取中转中心地址
                        var branchesLocationNearDto = GetTransferStation(mallOrderDto.Sender.Lng, mallOrderDto.Sender.Lat, 10);
                        if (branchesLocationNearDto == null)
                        {
                            //没有中转中心 就用车
                            var smallPrieceResult = vehicleSelectService.GetResult(mallOrderDto);
                            resultList.Add(smallPrieceResult);
                            mallOrderService.UpdateOrderTransportBusinessType(mallOrderDto.MallOrderNo, TransportBusinessType.SmallPieces);
                            return resultList;
                        }
                        else
                        {
                            MallOrderAddressEntity sender = mallOrderDto.Sender.As<MallOrderAddressEntity>();
                            MallOrderAddressEntity receiver = mallOrderDto.Receiver.As<MallOrderAddressEntity>();

                            //2.获取从商户发货地到中转中心跑腿费用 

                            mallOrderDto.Receiver.Lng = branchesLocationNearDto.Longitude;
                            mallOrderDto.Receiver.Lat = branchesLocationNearDto.Latitude;
                            mallOrderDto.Receiver.Address = branchesLocationNearDto.AgentBranchesName;

                            //3.获取从中转中心到目的地小件费用
                            var runErrandRseult = runErrandService.GetResult(mallOrderDto);
                            if (runErrandRseult.Result)
                            {
                                //拆单成功
                                //跑腿计算运费成功
                                mallOrderDto.Receiver.Lng = receiver.Lng;
                                mallOrderDto.Receiver.Lat = receiver.Lat;
                                mallOrderDto.Receiver.Address = receiver.Address;

                                mallOrderDto.Sender.Lng = branchesLocationNearDto.Longitude;
                                mallOrderDto.Sender.Lat = branchesLocationNearDto.Latitude;
                                mallOrderDto.Sender.Address = branchesLocationNearDto.AgentBranchesName;

                                var smallPrieceResult = vehicleSelectService.GetResult(mallOrderDto);
                                resultList.Add(runErrandRseult);
                                resultList.Add(smallPrieceResult);
                                if(smallPrieceResult.Result)
                                {
                                    mallOrderService.UpdateOrderSpilt(mallOrderDto.MallOrderNo, branchesLocationNearDto.AgentBranchesConfigId);
                                }
                                return resultList;
                            }
                            else
                            {
                                //拆单不成功
                                if (runErrandRseult.IsBeginCalcCost)
                                {
                                    resultList.Add(runErrandRseult);
                                    return resultList;
                                }
                                else
                                {
                                    mallOrderDto.Sender.Lng = sender.Lng;
                                    mallOrderDto.Sender.Lat = sender.Lat;
                                    mallOrderDto.Sender.Address = sender.Address;

                                    mallOrderDto.Receiver.Lng = receiver.Lng;
                                    mallOrderDto.Receiver.Lat = receiver.Lat;
                                    mallOrderDto.Receiver.Address = receiver.Address;


                                    var smallPrieceResult = vehicleSelectService.GetResult(mallOrderDto);
                                    resultList.Add(smallPrieceResult);
                                    mallOrderService.UpdateOrderTransportBusinessType(mallOrderDto.MallOrderNo, TransportBusinessType.SmallPieces);
                                    return resultList;
                                }
                            }
                        }
                    }
                }
                else
                {
                    var smallPrieceResult = vehicleSelectService.GetResult(mallOrderDto);
                    resultList.Add(smallPrieceResult);
                    return resultList;
                }
            }
            return null;

        }


        #endregion

        #region 获取最近的中转中心
        private BranchesLocationNearDto GetTransferStation(double lng,double lat,int distance)
        {
            var list = agentBranchesConfigService.GetList(lng, lat, distance);
            if(list !=null && list.Any())
            {
                return list.OrderBy(s => s.Dis).FirstOrDefault();
            }
            return null;
        }
        #endregion


        #region 订单确认
        public MallOrderConfirmResposeDto ConfirmOrder(MallOrderConfirmDto mallOrderConfirmDto)
        {
            MallOrderConfirmResposeDto mallOrderConfirmResposeDto = new MallOrderConfirmResposeDto();
            mallOrderConfirmResposeDto.MallOrderNo = mallOrderConfirmDto.MallOrderNo;
            //try
            {
                mallOrderService.CreateOrder(mallOrderConfirmDto);
                mallOrderConfirmResposeDto.Result = true;
            }
            //catch (System.Exception ex)
            //{
            //    mallOrderConfirmResposeDto.Result = false;
            //    mallOrderConfirmResposeDto.ResultDiscription = ex.Message;
            //}
            return mallOrderConfirmResposeDto;
        }
        #endregion

    }
}
